<template>
	<el-dialog :title="form.id ? '编辑' : '新增'" :visible.sync="visible" :close-on-click-modal="false">
		<el-form ref="form" :model="form" :rules="rules">
			<el-form-item label="卡券名称" :label-width="formLabelWidth" prop="name">
				<el-input v-model="form.name" autocomplete="off" placeholder="请输入卡券名称"></el-input>
			</el-form-item>
			<el-form-item label="兑换开始时间" :label-width="formLabelWidth" prop="startTime">
				<el-date-picker
					v-model="form.startTime"
					type="datetime"
					placeholder="选择日期时间"
					value-format="yyyy-MM-dd HH:mm:ss"
				></el-date-picker>
			</el-form-item>
			<el-form-item label="兑换截至时间" :label-width="formLabelWidth" prop="endTime">
				<el-date-picker
					v-model="form.endTime"
					type="datetime"
					placeholder="选择日期时间"
					value-format="yyyy-MM-dd HH:mm:ss"
				></el-date-picker>
			</el-form-item>
			<el-form-item label="最大兑换件数" :label-width="formLabelWidth" prop="maximum">
				<el-input-number v-model="form.maximum"></el-input-number>
			</el-form-item>
			<el-form-item label="兑换券类型" :label-width="formLabelWidth" prop="type">
				<fortress-radio-group v-model="form.type" :dictList="CodeType_exchangeList"></fortress-radio-group>
			</el-form-item>
			<el-form-item label="跳转url" v-if="form.type == 1" :label-width="formLabelWidth" prop="url">
				<el-input v-model="form.url" autocomplete="off" placeholder="请输入跳转URL"></el-input>
			</el-form-item>
			<el-form-item label="扫码绑定" :label-width="formLabelWidth" prop="isBind">
				<el-switch
					v-model="form.isBind"
					active-color="#13ce66"
					inactive-color="#ff4949"
					:active-value="1"
					:inactive-value="2"
				></el-switch>
			</el-form-item>
			<el-form-item label="商品" :label-width="formLabelWidth">
				<!-- <el-input v-model="displayGoodsName" autocomplete="off" placeholder="请选择商品"></el-input> -->
				<el-button @click="dialogTableVisible = true">选择商品</el-button>
				<el-table :data="checkGoods" v-if="checkGoods.length > 0">
					<el-table-column property="name" label="商品名称" width="460"></el-table-column>
					<el-table-column label="价格" :show-overflow-tooltip="true">
						<template slot-scope="scope">
							<p class="price">
								<span>￥{{ scope.row.marketPrice }}</span>
							</p>
						</template>
					</el-table-column>
					<el-table-column label="操作" fixed="right" min-width="100">
						<template slot-scope="scope">
							<el-button
								v-if="showConfigButton(scope.row)"
								icon="iconfont"
								size="mini"
								plain
								type="primary"
								@click="handleSetGoods(scope.row)"
							>
								商品设置
							</el-button>
							<el-button
								v-if="showButton(scope.row)"
								icon="iconfont"
								plain
								size="mini"
								type="danger"
								@click="handleRemoveGoods(scope.row)"
							>
								取消
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-form-item>
			<el-form-item label="邮费类型" :label-width="formLabelWidth" prop="postageType">
				<fortress-radio-group v-model="form.postageType" :dictList="PostageType_exchangeList"></fortress-radio-group>
			</el-form-item>
			<el-form-item label="邮费" :label-width="formLabelWidth" prop="postage">
				<el-input-number v-model="form.postage"></el-input-number>
			</el-form-item>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button @click="visible = false" size="medium" type="danger">取 消</el-button>
			<el-button type="primary" size="medium" @click="submitForm('form')">确 定</el-button>
		</div>
		<el-dialog title="选择商品" :visible.sync="dialogTableVisible" append-to-body>
			<el-row style="margin-bottom: 7px">
				<el-form :inline="true" :model="queryForm" @submit.native.prevent @keyup.enter.native="queryList">
					<el-form-item>
						<el-input
							prefix-icon="el-icon-search"
							v-model="queryForm.name"
							autocomplete="off"
							placeholder="请输入商品名称"
							clearable
						></el-input>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" size="medium" icon="el-icon-search" @click="queryList({ current: 1 })">查询</el-button>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" size="medium" icon="el-icon-refresh-left" @click="resetQueryForm">重置</el-button>
					</el-form-item>
				</el-form>
				<div style="float: right; padding-right: 17px">
					<el-tooltip class="item" effect="dark" content="刷新" placement="top">
						<i class="el-icon-refresh" style="margin-right: 10px; cursor: pointer" @click="refresh"></i>
					</el-tooltip>
				</div>
			</el-row>

			<el-table :data="gridData">
				<el-table-column property="name" label="商品名称" width="460"></el-table-column>
				<el-table-column label="价格" :show-overflow-tooltip="true">
					<template slot-scope="scope">
						<p class="price">
							<span>￥{{ scope.row.marketPrice }}</span>
						</p>
					</template>
				</el-table-column>
				<el-table-column prop="type" label="类型" :show-overflow-tooltip="true" :formatter="typeFmt" width="120"></el-table-column>
				<el-table-column prop="total" label="库存" :show-overflow-tooltip="true"></el-table-column>
				<el-table-column prop="remark" label="备注" :show-overflow-tooltip="true"></el-table-column>
				<el-table-column label="操作" fixed="right" min-width="100">
					<template slot-scope="scope">
						<el-button v-if="!showButton(scope.row)" icon="iconfont" plain type="primary" @click="handleAddGoods(scope.row)">
							选择
						</el-button>
						<el-button v-if="showButton(scope.row)" icon="iconfont" plain type="danger" @click="handleRemoveGoods(scope.row)">
							取消
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<pagination :total="page.total" :current-page="page.current" :page-size="page.size" @refreshData="queryList"></pagination>
		</el-dialog>
	</el-dialog>
</template>
<script>
import { exchangeconfigInfo, exchangeconfigSave, exchangeconfigEdit } from "@/api/exchange/exchangeconfig.js"
import FortressPagination from "@/components/fortress-pagination.vue"
import { goodsPage } from "@/api/goods/goods.js"
import { goodsspecList } from "@/api/goods/goodsspec.js"
import { enumList } from "@/api/public.api.js"
import * as ftVal from "@/common/fortressValidator.js"

export default {
	data() {
		return {
			displayGoodsName: "",
			gridData: [],
			queryForm: {
				name: "",
			},
			page: {
				current: 1,
				size: 10,
				total: 0,
			},
			dialogTableVisible: false,
			visible: false,
			form: {
				url: "",
				name: "",
				startTime: "",
				endTime: "",
				maximum: "",
				type: "",
				isBind: "2",
				goodsId: "",
				postageType: "",
				postage: "",
			},
			formLabelWidth: "120px",
			rules: {
				name: [{ required: true, message: "请输入卡券名称", trigger: "blur" }],
				startTime: [{ required: true, message: "请输入兑换开始时间", trigger: "blur" }],
				endTime: [{ required: true, message: "请输入兑换截至时间", trigger: "blur" }],
				maximum: [
					{ required: true, message: "请输入最大兑换件数", trigger: "blur" },
					{ validator: ftVal.validatePInteger, trigger: "blur" },
				],
				type: [{ required: true, message: "请输入兑换券类型", trigger: "blur" }],
				isBind: [{ required: true, message: "请输入扫码绑定", trigger: "blur" }],
				goodsId: [{ required: true, message: "请输入商品ID", trigger: "blur" }],
				postageType: [{ required: true, message: "请输入邮费类型", trigger: "blur" }],
				postage: [
					{ required: true, message: "请输入邮费", trigger: "blur" },
					{ validator: ftVal.validateTwoPoint, trigger: "blur" },
				],
			},
			CodeType_exchangeList: [],
			YesNoList: [],
			PostageType_exchangeList: [],
			GoodsType_goodsList: [],
			checkGoods: [],
		}
	},
	components: {
		pagination: FortressPagination,
	},
	created() {},
	methods: {
		refresh() {
			this.gridData = []
			this.queryList({ current: 1 })
		},
		resetQueryForm() {
			this.queryForm = {
				name: "",
				categoryId: "",
			}
		},
		handleAddGoods(goods) {
			this.checkGoods.push(goods)
		},
		handleSetGoods(goods) {
			goodsspecList({ goodsId: goods.id }).then(res => {
				console.log("res", res)
			})
		},
		handleRemoveGoods(goods) {
			for (let i = 0; i < this.checkGoods.length; i++) {
				if (this.checkGoods[i].id === goods.id) {
					this.checkGoods.splice(i, 1)
					break
				}
			}
		},
		typeFmt(row) {
			let name = ""
			if (this.GoodsType_goodsList) {
				this.GoodsType_goodsList.forEach(item => {
					if (item.code == row.type) {
						name = item.name
					}
				})
			}
			return name
		},
		showConfigButton(row) {
			return row.isSpec == 1
		},
		showButton(row) {
			let flag = false
			this.checkGoods.forEach(item => {
				if (row.id == item.id) {
					flag = true
				}
			})
			return flag
		},
		queryEnumList() {
			this.GoodsType_goodsList = []
			enumList("GoodsType", "goods").then(resp => {
				if (resp.code == 0) {
					this.GoodsType_goodsList = resp.data
				}
			})
			this.CodeType_exchangeList = []
			enumList("CodeType", "exchange").then(resp => {
				if (resp.code == 0) {
					this.CodeType_exchangeList = resp.data
				}
			})
			this.YesNoList = []
			enumList("YesNo", "").then(resp => {
				if (resp.code == 0) {
					this.YesNoList = resp.data
				}
			})
			this.PostageType_exchangeList = []
			enumList("PostageType", "exchange").then(resp => {
				if (resp.code == 0) {
					this.PostageType_exchangeList = resp.data
				}
			})
		},
		init(id) {
			this.resetForm()
			this.resetQueryForm()
			this.queryEnumList()
			this.queryList()
			//修改
			if (id) {
				exchangeconfigInfo(id).then(resp => {
					if (resp.code == 0) {
						this.$nextTick(() => {
							this.form = {
								...this.form,
								...resp.data,
							}
						})
					} else {
						this.$msg({
							message: resp.msg,
							type: "error",
						})
					}
				})
			}
			this.visible = true
		},
		queryList(page) {
			if (page) {
				this.page.current = page.current ? page.current : this.page.current
				this.page.size = page.size ? page.size : this.page.size
			}
			this.queryForm.current = this.page.current
			this.queryForm.size = this.page.size
			goodsPage(this.queryForm).then(resp => {
				if (resp.code == 0) {
					this.gridData = resp.data.records
					this.page.total = resp.data.total
					//查询页大于总页数，重新查询
					let cu =
						this.page.total % this.page.size == 0
							? parseInt(this.page.total / this.page.size)
							: parseInt(this.page.total / this.page.size + 1)
					if (cu > 0 && this.page.current > cu) {
						this.queryList({ current: cu })
					}
				} else {
					this.$msg({
						message: resp.msg,
						type: "error",
					})
				}
			})
		},
		//提交表单数据
		submitForm() {
			this.$refs["form"].validate(valid => {
				//todo 如果存在多规格 但是没有设置规格的商品就报错
				if (valid) {
					//修改
					if (this.form.id) {
						exchangeconfigEdit(this.form).then(resp => {
							if (resp.code == 0) {
								this.$message({
									type: "success",
									message: "操作成功!",
								})
								this.$emit("refreshData")
								this.visible = false
							} else {
								this.$msg({
									message: resp.msg,
									type: "error",
								})
							}
						})
						//新增
					} else {
						exchangeconfigSave(this.form).then(resp => {
							if (resp.code == 0) {
								this.$message({
									type: "success",
									message: "操作成功!",
								})
								this.$emit("refreshData")
								this.visible = false
							} else {
								this.$msg({
									message: resp.msg,
									type: "error",
								})
							}
						})
					}
				} else {
					console.log("error submit!!")
					return false
				}
			})
		},
		resetForm() {
			this.form = {
				url: "",
				name: "",
				startTime: "",
				endTime: "",
				maximum: "",
				type: "",
				isBind: "2",
				goodsId: "",
				postageType: "",
				postage: "",
			}
			this.checkGoods = []
			this.$nextTick(() => {
				if (this.$refs["form"]) {
					this.$refs["form"].resetFields()
				}
			})
		},
	},
}
</script>
<style scoped>
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}

.avatar-uploader .el-upload:hover {
	border-color: #409eff;
}

.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}

.avatar {
	width: 178px;
	height: 178px;
	display: block;
}

.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
	height: auto;
	max-height: 274px;
	padding: 7px;
	overflow: hidden;
	overflow-y: auto;
	font-weight: normal;
}
</style>
